<?php
/**
 * Description of CYuiTable
 *
 * @author ADMIN
 */
class CYuiTable
{
    protected static function getFieldNames($cols)
    {
       $rez = array();
       foreach($cols as $col)
        {
            switch($col['type'])
            {
                case 'date': $rez[] = array('key'=>$col['key'], 'parser'=>'date'); break;
                case 'number': $rez[] = array('key'=>$col['key'], 'parser'=>'number'); break;
                case 'boolean': $rez[] = array('key'=>$col['key'], 'parser'=>'boolean'); break;
                default: $rez[] = array('key'=>$col['key']);
            }
        }
       return $rez;
    }

    /*************** COLUMN FUNCTIONS ********************/
    // Get all columns definition for DB table
    public static function getAllColumnsFromTable($tableName)
    {
        $m = new $tableName;
        $dbCols = $m->metaData->columns;
        $cols = array();
        foreach($dbCols as $dbCol)
        {
            $colType = 'text'; $readOnly = false;
            $precision = $dbCol->precision; $scale = 0;
            if( (false !== strpos($dbCol->dbType, 'decimal')) ||
                (false !== strpos($dbCol->dbType, 'double')))
            {
                $colType = 'number';
                $scale = $dbCol->scale;
            }
            if(false !== strpos($dbCol->dbType, 'int('))
            {
                $colType = 'number';
                $scale = 0;
            }
            if( (false !== strpos($dbCol->dbType, 'text')) ||
                (false !== strpos($dbCol->dbType, 'blob')) )
            {
                $colType = 'textarea'; $precision = 0;
            }
            switch($dbCol->dbType)
            {
                case 'datetime':
                case 'date'    : $colType = 'date'; $precision = 0; break;
                case 'timestamp': $colType = 'date'; $precision = 0; $readOnly = true; break;
                case 'tinyint(1)':
                case 'tinyint(1) unsigned': $colType = 'boolean'; $precision = 0; break;
            }

            $cols[] = array('key'=>$dbCol->name, 'label'=>$m->getAttributeLabel($dbCol->name),
                'type'=>$colType,
                'precision'=>$precision, 'scale'=>$scale,
                'readOnly'=>$readOnly, 'sortable'=>true, 'resizeable'=>true, 
                'hidden'=>false, 'disableBtns'=>false,
                'pk'=>$dbCol->isPrimaryKey);
        }
        return $cols;
    }
    public static function columnCreate($fieldName, $title, $type, $precision, $scale = 0, $isPrimaryKey = false, $readOnly = false, $sortable = true, $resizeable = true, $disableBtns = false, $cssStyleName = null)
    {
        $rezArray =  array('key'=>$fieldName, 'label'=>$title, 'type'=>$type,
                           'precision'=>$precision, 'scale'=>$scale, 'readOnly'=>$readOnly,
                           'sortable'=>$sortable, 'resizeable'=>$resizeable, 'visible'=>true,
                           'disableBtns'=>$disableBtns, 'pk'=>$isPrimaryKey);
        if(isset($cssStyleName)) $rezArray['className'] = $cssStyleName;
        return $rezArray;
    }
    public static function columnAdd(&$columns, $newColumn)
    {
        $columns[] = $newColumn;
    }
    public static function columnHide(&$columns, $fieldName)
    {
        foreach($columns as $idx=>$c)
            if($c['key']==$fieldName)
            {
                $columns[$idx]['hidden']=true;
                break;
            }
    }
    public static function columnSetAttribute(&$columns, $columnName, $columnAttribute, $newValue)
    {
        foreach($columns as $idx=>$c)
            if($c['key']==$columnName)
            {
                $columns[$idx][$columnAttribute]=$newValue;
                break;
            }
    }
    /*public static function columnSetLookup(&$columns, $columnName, $tableFrom, $tableFromId, $tableFromLabel)
    {
        foreach($columns as $idx=>$c)
            if($c['key']==$columnName)
            {
                $columns[$idx]['type']='dropdown';
                $columns[$idx]['scale']= 0;
                $columns[$idx]['readOnly']= false;
                $columns[$idx]['hidden']= false;
                //$columns[$idx]['from']= $tableFrom;
                //$columns[$idx]['fromId']= $tableFromId;
                //$columns[$idx]['fromLabel']= $tableFromLabel;
                $sql = 'select '. $tableFromLabel.' as label, '.$tableFromId.' as value from '.$tableFrom.' order by '.$tableFromLabel;
                $command = Yii::app()->db->createCommand($sql);
                $rows = $command->queryAll();
                $columns[$idx]['dropdownOpt'] = json_encode($rows);
                break;
            }
    }*/
    /**************** PAGINATOR FUNCTIONS ***************/
    public static function paginatorCreate($rowsPerPage = 10)
    {
        return array('rowsPerPage'=>$rowsPerPage);
    }
    /* Set template for paginator
     * Sample:
     * '<h3>Header for table</h3>' +
     * '<p>{CurrentPageReport}' +
     * '{FirstPageLink} {PreviousPageLink} ' +
     * '{NextPageLink} {LastPageLink}' +
     * '<label>Page size: {RowsPerPageDropdown}</label>' +
     * '{PageLinks}</p>',
     */
    public static function paginatorSetTemplate(&$paginator, $template)
    {
        $paginator['template']=$template;
    }
    /* set dropdown list for select rows count on the page
     * sample { value : 10, text : "10" },
     *        { value : 50, text : "50" },
     *        { value : 1000000, text : "All" }
     */
    public static function paginatorRowsPerPageDropdown(array &$paginator, array $dropdownList)
    {
        $paginator['rowsPerPageOptions']=$dropdownList;
    }
    /* set "Page 1 from XX" */
    public static function paginatorSetPageReportTemplate(array &$paginator)
    {
        $lang = self::getLangArray();
        $paginator['pageReportTemplate'] = '('.$lang['page'].' {currentPage} '.$lang['from'].' {totalPages})';
    }
    public static function paginatorSetNavigationLabel(array &$paginator, $pageLinkCount, $firstPageLabel, $prevPageLabel, $nextPageLabel, $lastPageLabel)
    {
        $paginator['firstPageLinkLabel'] = $firstPageLabel;
        $paginator['previousPageLinkLabel'] = $prevPageLabel;
        $paginator['nextPageLinkLabel'] = $nextPageLabel;
        $paginator['lastPageLinkLabel'] = $lastPageLabel;
        $paginator['pageLinks'] = $pageLinkCount;
    }

    /****************** TABLE FUNCTIONS *****************/
    // Create Table Widget
    public static function tableCreate($tableName, $responseUrl = null, $paginator = null)
    {
        $initOptions = CYui::getLocalize('table');
        if(!isset($paginator)) $paginator = self::paginatorCreate();
        $initOptions['initialRequest'] = 'from=0?size='.$paginator['rowsPerPage'];
        $initOptions['dynamicData'] = true;
        $initOptions['selectionMode'] = 'single';
        $initOptions['dateOptions'] = array('format'=>CYui::getDefaultDateFormat(), 'locale'=>Yii::app()->language);
        return array('id'=>$tableName,
                     'responseUrl'=>(isset($responseUrl))? $responseUrl : '/yui/datatable/table/'.$tableName,
                     'paginator'=>$paginator,
                     'dateDBformat'=>CYui::getDbDateFormat(),
                     'calendar'=>CYui::buildCalendarOptions(),
                     'contextMenu'=>true,
                     'initOptions'=>$initOptions);
    }
    public static function tableSetSize(&$table, $width = null, $height = null)
    {
        if(isset($width))  $table['initOptions']['width'] = $width;
        if(isset($height)) $table['initOptions']['height'] = $height;
    }
    public static function tableHideContextMenu(&$table, $hide) { $table['contextMenu'] = (bool) !$hide; }
    public static function tableSetPaginator(&$table, $paginator)
    {
        $table['paginator'] = $paginator;
        $table['initOptions']['initialRequest'] = 'from=0&size='.$paginator['rowsPerPage'];
    }
    public static function tableSetResponseUrl(&$table, $responseUrl)
    {
        $table['responseUrl'] = $responseUrl;
    }
    public static function tableSetDateFormat(&$table, $dateFormat)
    {
        $table['dateOptions']['format'] = $dateFormat;
    }
    public static function tableSetColumns(&$table, $columns)
    {
        $table['columns'] = $columns;
    }
    public static function tableRender($table)
    {
        $responseSchema = array(
            'resultsList'=>'records',
            'fields'=>self::getFieldNames($table['columns']),
            'metaFields'=>array('totalRecords'=>'totalRecords')
        );
        $table['responseSchema'] = $responseSchema;
        
        return '
        <div id="'.$table['id'].'table"></div>
        <script type="text/javascript">
            var par'.$table['id'].' = '.json_encode($table).';
            YAHOO.util.Get.script("'.CYui::getLocalUrl().'wTable.js", {
                                       onSuccess: function() {
                                                    var table'.$table['id'].' = new YAHOO.YuiWidget.table;
                                                    table'.$table['id'].'.init(par'.$table['id'].') } })
         </script>
        ';
    }

}
?>
